Return the summation of an array


Posted by Christy on 2022-04-19

Description: Write a function named sum that accepts an array and return the summation of an array.

function sum(arr) {
  let result = 0;
  for (let i = 0; i < arr.length; i++) {
    result += arr[i];
  }
  return result;
}

console.log(sum([1, 2, 3])); // 6
console.log(sum([-1, 1, 2, -2, 3, -3])); // 0

The other answers:

function sum(arr) {
  let i = 0;
  let result = 0;
  do {
    result += arr[i];
    i++;
  } while (i < arr.length);
  return result;
}

console.log(sum([1, 2, 3])); // 6
console.log(sum([-1, 1, 2, -2, 3, -3])); // 0
function sum(arr) {
  let i = 0;
  let result = 0;
  while (i < arr.length) {
    result += arr[i];
    i++;
  }
  return result;
}

console.log(sum([1, 2, 3])); // 6
console.log(sum([-1, 1, 2, -2, 3, -3])); // 0









Related Posts

[Day 02] 工廠模式,策略模式,裝飾者模式

[Day 02] 工廠模式,策略模式,裝飾者模式

【單元測試的藝術】Chap 3: 透過虛設常式解決依賴問題

【單元測試的藝術】Chap 3: 透過虛設常式解決依賴問題

[C#] PdfTemplate.iTextSharp.LGPLv2 產生Pdf 範例

[C#] PdfTemplate.iTextSharp.LGPLv2 產生Pdf 範例


Comments